#!/bin/bash

. $ZMICRO_HOME/commands/machine/veth/config

is_namepsace_created() {
  sudo ip netns ls | grep $NETWORK_NAMESPACE >>/dev/null 2>&1
  if [ "$?" = "0" ]; then
    echo "true"
    return
  fi

  echo "false"
}

remove_namespace() {
  sudo ip netns del $NETWORK_NAMESPACE
}

remove_bridge() {
  sudo ip link del $NETWORK_BRIDGE

  sudo iptables -L FORWARD -v | grep ${NETWORK_BRIDGE} >>/dev/null 2>&1
  if [ "$?" = "0" ]; then
    sudo iptables -D FORWARD -o ${NETWORK_BRIDGE} -j ACCEPT
    sudo iptables -D FORWARD -i ${NETWORK_BRIDGE} -j ACCEPT

    # @TODO
    sudo iptables -t nat -D POSTROUTING -s ${NETWORK_MASK} -j MASQUERADE
  fi
}

remove_eth() {
  sudo ip netns exec $NETWORK_NAMESPACE ip link del $1-0
}

clear() {
  # remove_eth zmicro_veth10
  # remove_eth zmicro_veth11

  if [ "$(is_namepsace_created)" = "true" ]; then
    remove_namespace
    remove_bridge
  fi
}

help() {
  echo "Usage:"
  echo "  zmachine veth clear"
  echo ""
}

core() {
  if [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
    help
    exit 0
  fi

  clear
}

run() {
  core $@
}

run $@
